<?php

namespace app\modules\admin\forms;

use app\common\forms\BaseForm;
use app\models\Admin;
use app\modules\admin\services\AdminService;
use Yii;

/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends BaseForm
{
    public $username;
    public $password;

    /**
     * @var Admin $_user
     */
    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['username','password'],'filter','filter'=>'trim'],
            ['username', 'required','message'=>Yii::t("app","用户名不能为空")],
            ['password', 'required','message'=>Yii::t("app","密码不能为空")],
            ['password', 'validatePassword','params'=> [
                'user_message'=>Yii::t("app","用户不存在"),
                'pwd_message'=>Yii::t("app","用户名或密码错误")
            ]],
        ];
    }

    //验证密码
    public function validatePassword($attribute, $params)
    {
        if(!$this->hasErrors()) {
            $user = $this->getUser();

            //判断用户是否存在并且密码是否正确
            if (!$user) //判断用户是否存在
            {
                $this->addError("username",$params['user_message']);
                return;
            }
            if(!Yii::$app->getSecurity()->validatePassword($this->$attribute,$user->password))
            {
                $this->addError($attribute,$params['pwd_message']);
            }
        }
    }

    //帐号登录
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->getModule("admin")->get("user")->login($this->getUser());
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return Admin|null
     */
    public function getUser()
    {
        if (!$this->_user) {
            $this->_user = AdminService::loginByUserName($this->username);
        }
        return $this->_user;
    }
}
